package com.example.springbootflowabledemo.service.impl.sys;


import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootflowabledemo.domian.pojo.sys.SysUser;
import com.example.springbootflowabledemo.domian.pojo.sys.SysUserDept;
import com.example.springbootflowabledemo.domian.req.UserDistributeDeptReq;
import com.example.springbootflowabledemo.domian.req.UserLoginReq;
import com.example.springbootflowabledemo.exception.ServiceException;
import com.example.springbootflowabledemo.mapper.sys.SysUserDeptMapper;
import com.example.springbootflowabledemo.mapper.sys.SysUserMapper;
import com.example.springbootflowabledemo.service.sys.SysUserService;
import com.example.springbootflowabledemo.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@DS("sys")
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserDeptMapper sysUserDeptMapper;

    @Override
    public Boolean addUser(SysUser user) {
        log.info("新增用户, user={}", user);
        SysUser dbUser = this.lambdaQuery()
                .eq(SysUser::getUsername, user.getUsername())
                .one();
        if (dbUser != null) {
            throw new ServiceException("用户名已存在");
        }

        return this.save(user);
    }

    @Override
    public Boolean deleteUser(Long[] ids) {
        log.info("删除用户, ids={}", JSON.toJSONString(ids));
        return this.removeBatchByIds(Arrays.asList(ids));
    }

    @Override
    public Page<SysUser> listUser(Page<SysUser> page) {
        page = this.page(page,
                new QueryWrapper<SysUser>()
                        .lambda()
                        .select(SysUser::getUsername, SysUser::getId, SysUser::getNickname)
        );
        return page;
    }

    @Override
    public void userDistributeDept(UserDistributeDeptReq req) {
        SysUserDept sysUserDept = sysUserDeptMapper.selectOne(
                new QueryWrapper<SysUserDept>()
                        .lambda()
                        .eq(SysUserDept::getUserId, req.getUserId())
        );
        if(sysUserDept != null){
            throw new ServiceException("用户已经分配过部门");
        }
        SysUserDept userDept = new SysUserDept();
        BeanUtils.copyProperties(req, userDept);
        sysUserDeptMapper.insert(userDept);
    }

    @Override
    public Map login(UserLoginReq req) {
        if (StringUtils.isBlank(req.getUsername()) || StringUtils.isBlank(req.getPwd())) {
            log.error("username={}, password={}", req.getUsername(), req.getPwd());
            throw new ServiceException("登录失败!");
        }

        SysUser user = this.getOne(
                new QueryWrapper<SysUser>()
                        .lambda()
                        .eq(SysUser::getUsername, req.getUsername())
                        .eq(SysUser::getPwd, req.getPwd())
        );
        if (user == null) {
            log.error("{} 用户不存在", req.getUsername());
            throw new ServiceException("用户不存在!");
        }

        if (!user.getPwd().equals(req.getPwd())) {
            throw new ServiceException("密码错误!");
        }
        Map<String, String> map = new HashMap<>();
        map.put("nickname", user.getNickname());
        map.put("token", JwtUtil.sign(user.getUsername(), user.getId()));
        return map;
    }

    @Override
    public SysUser getUserById(String id) {
        return this.getById(Long.valueOf(id));
    }
}
